<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="班次名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班次名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班次编码" prop="classCode">
        <el-input
          v-model="queryParams.classCode"
          placeholder="请输入班次编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否免费" prop="isFree">
        <el-select v-model="queryParams.isFree" placeholder="请选择是否免费" clearable>
          <el-option label="是" :value="1"></el-option>
          <el-option label="否" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否公开" prop="isPublic">
        <el-select v-model="queryParams.isPublic" placeholder="请选择是否公开" clearable>
          <el-option label="是" :value="1"></el-option>
          <el-option label="否" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否精选" prop="isFeatured">
        <el-select v-model="queryParams.isFeatured" placeholder="请选择是否精选" clearable>
          <el-option label="是" :value="1"></el-option>
          <el-option label="否" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <!-- 0招生、1考试、2结束 -->
      <el-form-item label="班次状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择班次状态" clearable>
          <el-option label="招生" :value="0"></el-option>
          <el-option label="考试" :value="1"></el-option>
          <el-option label="结束" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班次分类" prop="categoryId">
        <el-select v-model="queryParams.categoryId" placeholder="请选择班次分类" clearable>
          <el-option 
            v-for="category in classCategoryList" 
            :key="category.id" 
            :label="category.categoryName" 
            :value="category.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:class:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:class:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:class:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['course:class:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-download"
          size="mini"
          @click="handleDownloadTemplate"
        >下载模板</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="班次名称" align="center" prop="className" width="250" />
      <el-table-column label="班次编码" align="center" prop="classCode" />
      <el-table-column label="班次分类" align="center" prop="categoryName" width="120" />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报名开始时间" align="center" prop="registerStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registerStartTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报名结束时间" align="center" prop="registerEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registerEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="原价" align="center" prop="originalPrice" />
      <el-table-column label="现价" align="center" prop="currentPrice" />
      <el-table-column label="是否免费" align="center" prop="isFree">
        <template slot-scope="scope">
          <span>{{ scope.row.isFree === 1 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班次管理人" align="center" prop="classManager" />
      <el-table-column label="联系方式" align="center" prop="classContact" />
      <el-table-column label="班次状态" align="center" prop="status" />
      <el-table-column label="是否公开" align="center" prop="isPublic">
        <template slot-scope="scope">
          <span>{{ scope.row.isPublic === 1 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否精选" align="center" prop="isFeatured">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isFeatured === 1 ? 'success' : 'info'" size="mini">
            {{ scope.row.isFeatured === 1 ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="240">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['course:class:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:class:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:class:remove']"
          >删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['monitor:job:changeStatus', 'monitor:job:query']">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="importStudent" icon="el-icon-caret-right">导入学员</el-dropdown-item>
              <el-dropdown-item command="addStudent" icon="el-icon-plus" >新增学员</el-dropdown-item>
              <el-dropdown-item command="studentList" icon="el-icon-user" >学员列表</el-dropdown-item>
              <el-dropdown-item command="relatedCourse" icon="el-icon-s-operation" >关联课程</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考试班次对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="班次名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班次名称" />
        </el-form-item>
        <el-form-item label="班次编码" prop="classCode">
          <el-input v-model="form.classCode" placeholder="请输入班次编码" />
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImage">
          <image-upload 
            v-model="form.coverImage"
            :limit="1"
            :file-size="5"
            :file-type="['png', 'jpg', 'jpeg']"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程开始时间" prop="startTime">
              <el-date-picker clearable
                v-model="form.startTime"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择开始时间"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程结束时间" prop="endTime">
              <el-date-picker clearable
                v-model="form.endTime"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择结束时间"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报名开始时间" prop="registerStartTime">
              <el-date-picker clearable
                v-model="form.registerStartTime"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择报名开始时间"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报名结束时间" prop="registerEndTime">
              <el-date-picker clearable
                v-model="form.registerEndTime"
                type="date"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择报名结束时间"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="考试时长" prop="examDuration">
          <el-input v-model="form.examDuration" placeholder="请输入考试时长" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原价" prop="originalPrice">
              <el-input v-model="form.originalPrice" placeholder="请输入原价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="现价" prop="currentPrice">
              <el-input v-model="form.currentPrice" placeholder="请输入现价" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否免费" prop="isFree">
          <el-switch
            v-model="form.isFree"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否">
          </el-switch>
        </el-form-item>
        <el-form-item label="班次描述" prop="classDescription">
          <el-input v-model="form.classDescription" type="textarea" :rows="8" placeholder="请输入内容" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班次管理人" prop="classManager">
              <el-input v-model="form.classManager" placeholder="请输入班次管理人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="classContact">
              <el-input v-model="form.classContact" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="显示顺序" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入显示顺序" />
        </el-form-item>
        <el-form-item label="是否公开" prop="isPublic">
          <el-switch
            v-model="form.isPublic"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否">
          </el-switch>
        </el-form-item>
        <el-form-item label="是否精选" prop="isFeatured">
          <el-switch
            v-model="form.isFeatured"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否">
          </el-switch>
        </el-form-item>
        <el-form-item label="班次分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择班次分类" clearable>
            <el-option 
              v-for="category in classCategoryList" 
              :key="category.id" 
              :label="category.categoryName" 
              :value="category.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班次状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择班次状态" clearable>
            <el-option label="招生" :value="0"></el-option>
            <el-option label="考试" :value="1"></el-option>
            <el-option label="结束" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看班次详情对话框 -->
    <el-dialog title="班次详情" :visible.sync="viewOpen" width="70%" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="班次名称">
          {{ viewData.className }}
        </el-descriptions-item>
        <el-descriptions-item label="班次编码">
          {{ viewData.classCode }}
        </el-descriptions-item>
        <el-descriptions-item label="班次分类">
          {{ viewData.categoryName }}
        </el-descriptions-item>
        <el-descriptions-item label="封面图片">
          <image-preview 
            v-if="viewData.coverImage" 
            :src="viewData.coverImage" 
            :width="120" 
            :height="80"
          />
          <span v-else>暂无封面图片</span>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">
          {{ parseTime(viewData.startTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="结束时间">
          {{ parseTime(viewData.endTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="报名开始时间">
          {{ parseTime(viewData.registerStartTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="报名结束时间">
          {{ parseTime(viewData.registerEndTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="考试时长">
          {{ viewData.examDuration }} 分钟
        </el-descriptions-item>
        <el-descriptions-item label="原价">
          ￥{{ viewData.originalPrice }}
        </el-descriptions-item>
        <el-descriptions-item label="现价">
          ￥{{ viewData.currentPrice }}
        </el-descriptions-item>
        <el-descriptions-item label="是否免费">
          <el-tag :type="viewData.isFree === 1 ? 'success' : 'danger'">
            {{ viewData.isFree === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="班次管理人">
          {{ viewData.classManager }}
        </el-descriptions-item>
        <el-descriptions-item label="联系方式">
          {{ viewData.classContact }}
        </el-descriptions-item>
        <el-descriptions-item label="显示顺序">
          {{ viewData.sortOrder }}
        </el-descriptions-item>
        <el-descriptions-item label="班次状态">
          <el-tag :type="viewData.status === 1 ? 'success' : 'info'">
            {{ viewData.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="是否公开">
          <el-tag :type="viewData.isPublic === 1 ? 'success' : 'warning'">
            {{ viewData.isPublic === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="是否精选">
          <el-tag :type="viewData.isFeatured === 1 ? 'success' : 'info'">
            {{ viewData.isFeatured === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ parseTime(viewData.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="班次描述" :span="2">
          {{ viewData.classDescription }}
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 学员导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?classId=' + upload.classId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="handleDownloadTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增学员对话框 -->
    <el-dialog title="新增学员" :visible.sync="addStudentOpen" width="500px" append-to-body>
      <el-form ref="studentForm" :model="studentForm" :rules="studentRules" label-width="80px">
        <el-form-item label="学员姓名" prop="userName">
          <el-input v-model="studentForm.userName" placeholder="请输入学员姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="studentForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCardNumber">
          <el-input v-model="studentForm.idCardNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="studentForm.gender" placeholder="请选择性别" style="width: 100%;">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStudentForm">确 定</el-button>
        <el-button @click="cancelAddStudent">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 学员列表对话框 -->
    <el-dialog :title="'学员列表 - ' + currentClassInfo.className" :visible.sync="studentListOpen" width="80%" append-to-body>
      <el-table v-loading="studentListLoading" :data="studentList" style="width: 100%">
        <el-table-column prop="userName" label="学员姓名" width="120"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="140"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80"></el-table-column>
        <el-table-column prop="createTime" label="加入时间" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleRemoveStudent(scope.row)"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="studentListTotal > 0"
        :total="studentListTotal"
        :page.sync="studentListQuery.pageNum"
        :limit.sync="studentListQuery.pageSize"
        @pagination="handleStudentListPagination"
        style="margin-top: 20px;"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="studentListOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 关联课程对话框 -->
    <el-dialog :title="'关联课程 - ' + currentClassInfo.className" :visible.sync="relatedCourseOpen" width="80%" append-to-body>
      <div style="margin-bottom: 16px;">
        <el-button 
          type="primary" 
          icon="el-icon-plus" 
          size="small" 
          @click="handleAddCourseRelation"
        >新增关联课程</el-button>
      </div>
      
      <el-table v-loading="courseListLoading" :data="relatedCourseList" style="width: 100%">
        <el-table-column prop="courseName" label="课程名称" width="200"></el-table-column>
        <el-table-column prop="courseCode" label="课程代码" width="150"></el-table-column>
        <el-table-column prop="courseDetail" label="课程详情" show-overflow-tooltip></el-table-column>
        <el-table-column prop="participantCount" label="参与人数" width="120"></el-table-column>
        <el-table-column prop="isFeatured" label="是否精选" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isFeatured === 1 ? 'success' : 'info'" size="mini">
              {{ scope.row.isFeatured === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              style="color: #f56c6c;"
              @click="handleRemoveCourseRelation(scope.row)"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="relatedCourseTotal > 0"
        :total="relatedCourseTotal"
        :page.sync="relatedCourseQuery.pageNum"
        :limit.sync="relatedCourseQuery.pageSize"
        @pagination="handleRelatedCoursePagination"
        style="margin-top: 20px;"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="relatedCourseOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增课程关联对话框 -->
    <el-dialog title="选择要关联的课程" :visible.sync="addCourseRelationOpen" width="70%" append-to-body>
      <el-alert
        title="提示：已关联的课程不会在列表中显示"
        type="info"
        show-icon
        :closable="false"
        style="margin-bottom: 16px;"
      ></el-alert>
      <el-form :model="courseSearchParams" ref="courseSearchForm" size="small" :inline="true" style="margin-bottom: 16px;">
        <el-form-item label="课程名称" prop="courseName">
          <el-input 
            v-model="courseSearchParams.courseName" 
            placeholder="请输入课程名称" 
            clearable 
            @keyup.enter.native="searchAvailableCourses"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="searchAvailableCourses">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetCourseSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table 
        v-loading="availableCourseListLoading" 
        :data="availableCourseList" 
        @selection-change="handleCourseSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="courseName" label="课程名称" width="200"></el-table-column>
        <el-table-column prop="courseCode" label="课程代码" width="150"></el-table-column>
        <el-table-column prop="courseDetail" label="课程详情" show-overflow-tooltip></el-table-column>
        <el-table-column prop="participantCount" label="参与人数" width="120"></el-table-column>
        <el-table-column prop="isFeatured" label="是否精选" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isFeatured === 1 ? 'success' : 'info'" size="mini">
              {{ scope.row.isFeatured === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="availableCourseTotal > 0"
        :total="availableCourseTotal"
        :page.sync="availableCourseSearchQuery.pageNum"
        :limit.sync="availableCourseSearchQuery.pageSize"
        @pagination="handleAvailableCoursePagination"
        style="margin-top: 20px;"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button 
          type="primary" 
          @click="submitCourseRelation" 
          :disabled="selectedCourses.length === 0 || submittingCourseRelation"
          :loading="submittingCourseRelation"
        >
          {{ submittingCourseRelation ? '关联中...' : `确定关联 (${selectedCourses.length})` }}
        </el-button>
        <el-button @click="cancelAddCourseRelation" :disabled="submittingCourseRelation">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClass, getClass, delClass, addClass, updateClass,importData,addClassStudent,getClassStudents,removeClassStudent,getClassCourses,addClassCourse,removeClassCourse } from "@/api/course/class";
import { listAllCourse } from "@/api/course/course";
import { listAllClassCategory } from "@/api/course/classCategory";
import { getToken } from "@/utils/auth";
import ImageUpload from "@/components/ImageUpload";
import ImagePreview from "@/components/ImagePreview";
export default {
  name: "Class",
  components: {
    ImageUpload,
    ImagePreview
  },
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考试班次表格数据
      classList: [],
      // 班次分类列表
      classCategoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查看对话框控制变量
      viewOpen: false,
      // 查看数据
      viewData: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        className: null,
        classCode: null,
        startTime: null,
        endTime: null,
        registerStartTime: null,
        registerEndTime: null,
        examDuration: null,
        originalPrice: null,
        currentPrice: null,
        isFree: null,
        classDescription: null,
        classManager: null,
        classContact: null,
        sortOrder: null,
        status: null,
        isPublic: null,
        isFeatured: null,
        categoryId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键ID不能为空", trigger: "blur" }
        ],
        className: [
          { required: true, message: "班次名称不能为空", trigger: "blur" }
        ],
        classCode: [
          { required: true, message: "班次编码不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        registerStartTime: [
          { required: true, message: "报名开始时间不能为空", trigger: "blur" }
        ],
        registerEndTime: [
          { required: true, message: "报名结束时间不能为空", trigger: "blur" }
        ],
        examDuration: [
          { required: true, message: "考试时长不能为空", trigger: "blur" }
        ],
        originalPrice: [
          { required: true, message: "原价不能为空", trigger: "blur" }
        ],
        currentPrice: [
          { required: true, message: "现价不能为空", trigger: "blur" }
        ],
        isFree: [
          { required: true, message: "是否免费不能为空", trigger: "blur" }
        ],
        classDescription: [
          { required: true, message: "班次描述不能为空", trigger: "blur" }
        ],
        classManager: [
          { required: true, message: "班次管理人不能为空", trigger: "blur" }
        ],
        classContact: [
          { required: true, message: "联系方式不能为空", trigger: "blur" }
        ],
        sortOrder: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "班次状态不能为空", trigger: "blur" }
        ],
        isPublic: [
          { required: true, message: "是否公开不能为空", trigger: "blur" }
        ],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "导入学员",
        // 是否禁用上传
        isUploading: false,
        // 班次ID
        classId: null,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/course/class/importData"
      },
      // 新增学员对话框控制变量
      addStudentOpen: false,
      // 当前操作的班次ID
      currentClassId: null,
      // 学员表单数据
      studentForm: {
        userName: null,
        phone: null,
        idCardNumber: null,
        gender: null,
        classId: null
      },
      // 学员表单验证规则
      studentRules: {
        userName: [
          { required: true, message: "学员姓名不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { pattern: /^1[3456789]\d{9}$/, message: "手机号格式不正确", trigger: "blur" }
        ],
        idCardNumber: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: "身份证号格式不正确", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ]
      },
      // 学员列表对话框控制变量
      studentListOpen: false,
      // 学员列表数据
      studentList: [],
      // 学员列表加载状态
      studentListLoading: false,
      // 学员列表总数
      studentListTotal: 0,
      // 学员列表查询参数
      studentListQuery: {
        pageNum: 1,
        pageSize: 10
      },
      // 当前查看学员列表的班次信息
      currentClassInfo: {},
      // 关联课程对话框控制变量
      relatedCourseOpen: false,
      // 关联课程列表数据
      relatedCourseList: [],
      // 关联课程列表加载状态
      courseListLoading: false,
      // 关联课程列表总数
      relatedCourseTotal: 0,
      // 关联课程列表查询参数
      relatedCourseQuery: {
        pageNum: 1,
        pageSize: 10
      },
      // 新增课程关联对话框控制变量
      addCourseRelationOpen: false,
      // 可选课程列表数据
      availableCourseList: [],
      // 可选课程列表加载状态
      availableCourseListLoading: false,
      // 可选课程列表总数
      availableCourseTotal: 0,
      // 可选课程搜索查询参数
      availableCourseSearchQuery: {
        pageNum: 1,
        pageSize: 10
      },
      // 课程搜索参数
      courseSearchParams: {
        courseName: null,
        courseCode: null
      },
      // 选中的课程列表
      selectedCourses: [],
      // 提交课程关联状态
      submittingCourseRelation: false
    };
  },
  created() {
    this.getList();
    this.getClassCategoryList();
  },
  methods: {
    /** 查询考试班次列表 */
    getList() {
      this.loading = true;
      listClass(this.queryParams).then(response => {
        this.classList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询班次分类列表 */
    getClassCategoryList() {
      listAllClassCategory().then(response => {
        this.classCategoryList = response.rows || response.data || [];
      }).catch(() => {
        this.classCategoryList = [];
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        className: null,
        classCode: null,
        coverImage: null,
        startTime: null,
        endTime: null,
        registerStartTime: null,
        registerEndTime: null,
        examDuration: null,
        originalPrice: null,
        currentPrice: null,
        isFree: 0,
        classDescription: null,
        classManager: null,
        classContact: null,
        sortOrder: null,
        status: 0,
        isPublic: 0,
        isFeatured: 0,
        categoryId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考试班次";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getClass(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改考试班次";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateClass(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClass(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除考试班次编号为"' + ids + '"的数据项？').then(function() {
        return delClass(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('course/class/export', {
        ...this.queryParams
      }, `class_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板操作 */
    handleDownloadTemplate() {
      this.download('course/class/importTemplate', {}, `课程班次人员名单模板.xlsx`)
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "importStudent":
          this.handleImportStudent(row);
          break;
        case "addStudent":
          this.handleAddStudent(row);
          break;
        case "studentList":
          this.handleStudentList(row);
          break;
        case "relatedCourse":
          this.handleRelatedCourse(row);
          break;
        default:
          break;
      }
    },
    /** 查看按钮操作 */
    handleView(row) {
      const id = row.id;
      getClass(id).then(response => {
        this.viewData = response.data;
        this.viewOpen = true;
      });
    },
    handleImportStudent(row) {
      this.upload.open = true;
      this.upload.classId = row.id;
      this.upload.url = process.env.VUE_APP_BASE_API + "/course/class/importData";
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handleAddStudent(row) {
      this.resetStudentForm();
      this.currentClassId = row.id;
      this.studentForm.classId = row.id;
      this.addStudentOpen = true;
    },
    // 重置学员表单
    resetStudentForm() {
      this.studentForm = {
        userName: null,
        phone: null,
        idCardNumber: null,
        gender: null,
        classId: null
      };
      this.$nextTick(() => {
        this.$refs.studentForm && this.$refs.studentForm.clearValidate();
      });
    },
    // 取消新增学员
    cancelAddStudent() {
      this.addStudentOpen = false;
      this.resetStudentForm();
    },
    // 提交学员表单
    submitStudentForm() {
      this.$refs["studentForm"].validate(valid => {
        if (valid) {
          addClassStudent(this.studentForm).then(response => {
            this.$modal.msgSuccess("新增学员成功");
            this.addStudentOpen = false;
            this.resetStudentForm();
          }).catch(error => {
            console.error("新增学员失败:", error);
          });
        }
      });
    },
    // 处理学员列表
    handleStudentList(row) {
      this.currentClassInfo = row;
      this.getStudentList();
      this.studentListOpen = true;
    },
    // 获取学员列表
    getStudentList() {
      this.studentListLoading = true;
      getClassStudents(this.currentClassInfo.id, this.studentListQuery).then(response => {
        this.studentList = response.rows;
        this.studentListTotal = response.total;
        this.studentListLoading = false;
      });
    },
    // 学员列表分页
    handleStudentListPagination(val) {
      this.studentListQuery.pageNum = val.page;
      this.studentListQuery.pageSize = val.limit;
      this.getStudentList();
    },
    // 移除学员
    handleRemoveStudent(row) {
      this.$modal.confirm('是否确认移除学员"' + row.userName + '"？').then(() => {
        return removeClassStudent(this.currentClassInfo.id, row.userId);
      }).then(() => {
        this.$modal.msgSuccess("移除学员成功");
        this.getStudentList();
      }).catch(() => {});
    },
    // 处理关联课程
    handleRelatedCourse(row) {
      this.currentClassInfo = row;
      this.resetRelatedCourseQuery();
      this.getRelatedCourseList();
      this.relatedCourseOpen = true;
    },
    // 重置关联课程查询参数
    resetRelatedCourseQuery() {
      this.relatedCourseQuery = {
        pageNum: 1,
        pageSize: 10
      };
    },
    // 获取关联课程列表
    getRelatedCourseList() {
      this.courseListLoading = true;
      getClassCourses(this.currentClassInfo.id, this.relatedCourseQuery).then(response => {
        this.relatedCourseList = response.rows;
        this.relatedCourseTotal = response.total;
        this.courseListLoading = false;
      }).catch(() => {
        this.courseListLoading = false;
      });
    },
    // 关联课程列表分页
    handleRelatedCoursePagination(val) {
      this.relatedCourseQuery.pageNum = val.page;
      this.relatedCourseQuery.pageSize = val.limit;
      this.getRelatedCourseList();
    },
    // 处理新增课程关联
    handleAddCourseRelation() {
      this.resetCourseSearch();
      this.getAvailableCourseList();
      this.addCourseRelationOpen = true;
    },
    // 重置课程搜索
    resetCourseSearch() {
      this.courseSearchParams = {
        courseName: null,
        courseCode: null
      };
      this.availableCourseSearchQuery = {
        pageNum: 1,
        pageSize: 10
      };
      this.selectedCourses = [];
      this.submittingCourseRelation = false;
    },
    // 搜索可选课程
    searchAvailableCourses() {
      this.availableCourseSearchQuery.pageNum = 1;
      this.getAvailableCourseList();
    },
    // 获取可选课程列表
    getAvailableCourseList() {
      this.availableCourseListLoading = true;
      const queryParams = {
        ...this.availableCourseSearchQuery,
        ...this.courseSearchParams
      };
      listAllCourse(queryParams).then(response => {
        let courseList = response.rows || response.data || [];
        
        // 过滤掉已经关联的课程
        const relatedCourseIds = this.relatedCourseList.map(course => course.id);
        courseList = courseList.filter(course => !relatedCourseIds.includes(course.id));
        
        this.availableCourseList = courseList;
        this.availableCourseTotal = courseList.length; // 注意：这里使用过滤后的长度
        this.availableCourseListLoading = false;
      }).catch(() => {
        this.availableCourseListLoading = false;
      });
    },
    // 可选课程列表分页
    handleAvailableCoursePagination(val) {
      this.availableCourseSearchQuery.pageNum = val.page;
      this.availableCourseSearchQuery.pageSize = val.limit;
      this.getAvailableCourseList();
    },
    // 课程选择变化
    handleCourseSelectionChange(selection) {
      this.selectedCourses = selection;
    },
    // 提交课程关联
    submitCourseRelation() {
      if (this.selectedCourses.length === 0) {
        this.$modal.msgWarning("请选择要关联的课程");
        return;
      }
      
      this.submittingCourseRelation = true;
      
      // 提取选中课程的ID列表
      const courseIds = this.selectedCourses.map(course => course.id);
      
      // 调用批量添加接口
      addClassCourse(this.currentClassInfo.id, courseIds).then(response => {
        this.$modal.msgSuccess(response.msg || `成功关联 ${this.selectedCourses.length} 个课程`);
        this.addCourseRelationOpen = false;
        this.getRelatedCourseList();
        this.resetCourseSearch();
      }).catch(error => {
        console.error("关联课程失败:", error);
        const errorMsg = error.response?.data?.msg || "关联课程失败，请重试";
        this.$modal.msgError(errorMsg);
      }).finally(() => {
        this.submittingCourseRelation = false;
      });
    },
    // 取消新增课程关联
    cancelAddCourseRelation() {
      this.addCourseRelationOpen = false;
      this.resetCourseSearch();
    },
    // 移除课程关联
    handleRemoveCourseRelation(row) {
      this.$modal.confirm('是否确认移除课程"' + row.courseName + '"的关联？').then(() => {
        return removeClassCourse(this.currentClassInfo.id, row.courseId);
      }).then(() => {
        this.$modal.msgSuccess("移除课程关联成功");
        this.getRelatedCourseList();
      }).catch(() => {});
    }
  }
};
</script>
